﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DIST.LR.ZHJG.Events;
using HSE.Events;
using Telerik.Windows.Controls;
using HSE.Common;

namespace HSE
{
    public partial class Navigation : UserControl
    {
        Storyboard _selectionSb;

        double _selectionWayLength;
        RadRadioButton _selectedRadioItem;

        public static readonly DependencyProperty SelectionMovingStateProperty = DependencyProperty.Register("SelectionMovingState", typeof(double), typeof(Navigation), new PropertyMetadata(0.0,
    (d, e) => ((Navigation)d).RaiseSelectionMovingStateChanged(e)));

        public double SelectionMovingState { get { return (double)GetValue(SelectionMovingStateProperty); } set { SetValue(SelectionMovingStateProperty, value); } }

        public NavigationViewModel viewmodel;


        public Navigation()
        {
            InitializeComponent();

            _selectionSb = (Storyboard)this.Resources["selectionSb"];
            _selectionSb.Completed += new EventHandler(_selectionSb_Completed);

            viewmodel = new NavigationViewModel();
            this.DataContext = viewmodel;
        }

        void _selectionSb_Completed(object sender, EventArgs e)
        {
            EventAggregatorRepository.EventAggregator
                .GetEvent<NaviClickEvent>()
                .Publish(new NaviClickInfo() { Owner="Home", NaviInfo = viewmodel.SelectNavigation });
        }

        void RaiseSelectionMovingStateChanged(DependencyPropertyChangedEventArgs e)
        {
            double newValue = (double)e.NewValue;
            double oldValue = (double)e.OldValue;
            if (SelectionMovingState != 0.0)
            {
                ((TranslateTransform)this.Selection.RenderTransform).Y -= _selectionWayLength * (newValue - oldValue);
            }
        }

        void StartSelectionRun()
        {
            if (_selectionSb == null) return;
            _selectionSb.Stop();
            _selectionWayLength = CalculateSelectionWayLength();
            Storyboard.SetTarget(_selectionSb, this);
            _selectionSb.Begin();
        }

        double CalculateSelectionWayLength()
        {
            return this.Selection.TransformToVisual(_selectedRadioItem).Transform(new Point(0.0, -1)).Y + (this.Selection.ActualHeight - _selectedRadioItem.ActualHeight) * 1.5;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _selectedRadioItem = (RadRadioButton)sender;
            viewmodel.SelectNavigation = ((RadRadioButton)sender).Tag as ToolBarNaviInfo;
            StartSelectionRun();
        }
    }
}
